package cn.etgps.etgps.ui;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import cn.etgps.etgps.R;
import cn.etgps.etgps.base.BaseActivity;
import cn.etgps.etgps.blmanager.TruckManager;
import cn.etgps.etgps.dataEntity.TrackReplayBean;
import cn.etgps.etgps.dataEntity.TruckBean;
import cn.etgps.etgps.dialog.DialogCreater;
import cn.etgps.etgps.utils.AppUtils;
import cn.etgps.etgps.utils.Constant;
import cn.etgps.etgps.view.TitleBar;

/**
 * 这是根据时间来设定轨迹回放
 */
public class TrackReplaySettingActivity extends BaseActivity implements View.OnClickListener {
    private static final int MAX_TIME_DURATION = 1000 * 60 * 60 * 24 * 3;
    /**
     * 存放轨迹信息的集合
     */
    public static ArrayList<TrackReplayBean> mLoactions;
    final Calendar mTemCalender = Calendar.getInstance();
    /**
     * 车牌号
     */
    private TextView mCarNumber;
    /**
     * 为了实现点击的layout
     */
    private RelativeLayout mStartYearGroup;
    private RelativeLayout mStartHourGroup;
    private RelativeLayout mEndYearGroup;
    private RelativeLayout mEndHourGroup;
    /**
     * 轨迹回放确认
     */
    private Button mTrackRepaly;
    /**
     * truckBean对象 主要是接收有适配器传来的truckBean
     */
    private TruckBean mTruckBean;
    /**
     * 开始时间年月日
     */
    private TextView mStartYear;
    /**
     * 开始时间小时分钟
     */
    private TextView mStartHour;
    /**
     * 结束时间年月日
     */
    private TextView mEndYear;
    /**
     * 结束时间小时分钟
     */
    private TextView mEndHour;
    private TruckManager mTrukManger = null;
    /**
     * 请求轨迹数据的线程
     */
    private TrackReplayTask mTrackReplayTask;
    private TitleBar mTitlebarView = null;
    /**
     * 系统时间Canlendar类型
     */
    private Calendar mSystemCalendar = null;
    /**
     * 开始时间date类型
     */
    private Date mStartDate = null;
    /**
     * 结束时间date类型
     */
    private Date mEndDate = null;
    /**
     * 设置选择小时分钟的变量 小时
     */
    private int mHour = 0;
    /**
     * 设置选择小时分钟的变量 分钟
     */
    private int mMinute = 0;
    /**
     * 记录是否是第一次点击设置
     */
    private int mCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_track_repaly_setting);
        init();
    }

    private void init() {
        mTitlebarView = (TitleBar) findViewById(R.id.title_bar);
        mTitlebarView.initTitleBarInfo(getString(R.string.label_truck_playback_set), "", R.drawable.icon_return, "", 0,
                false);
        mTitlebarView.setMainClickListener(this, getString(R.string.btn_back), "");
        mTruckBean = (TruckBean) getIntent().getSerializableExtra("Model");
        mTrukManger = new TruckManager(this);
        mCarNumber = (TextView) findViewById(R.id.carNumber);
        mStartYearGroup = (RelativeLayout) findViewById(R.id.start_year_month_day_group);
        mStartHourGroup = (RelativeLayout) findViewById(R.id.start_hour_minute_group);
        mEndYearGroup = (RelativeLayout) findViewById(R.id.end_year_moth_day_group);
        mEndHourGroup = (RelativeLayout) findViewById(R.id.end_hour_minute_group);
        mTrackRepaly = (Button) findViewById(R.id.trackRepaly);
        mStartYear = (TextView) findViewById(R.id.startYearMothDay);
        mStartHour = (TextView) findViewById(R.id.startHourMinute);
        mEndYear = (TextView) findViewById(R.id.endYearMothDay);
        mEndHour = (TextView) findViewById(R.id.endHourMinute);
        mStartYearGroup.setOnClickListener(this);
        mStartHourGroup.setOnClickListener(this);
        mEndYearGroup.setOnClickListener(this);
        mEndHourGroup.setOnClickListener(this);
        mTrackRepaly.setOnClickListener(this);
        mCarNumber.setText(mTruckBean.getLicense());
        mSystemCalendar = AppUtils.getCurrentSystemDate();
        mEndDate = mSystemCalendar.getTime();
        mSystemCalendar.set(Calendar.DAY_OF_MONTH, mSystemCalendar.get(Calendar.DAY_OF_MONTH) - 1);
        mSystemCalendar.set(Calendar.HOUR_OF_DAY, 0);
        mSystemCalendar.set(Calendar.MINUTE, 0);
        mStartDate = mSystemCalendar.getTime();
        mStartYear.setText(AppUtils.getCurrentDate(mStartDate));
        mEndYear.setText(AppUtils.getCurrentDate(mEndDate));
        mStartHour.setText(AppUtils.getCurrentTime(mStartDate));
        mEndHour.setText(AppUtils.getCurrentTime(mEndDate));
    }

    @Override
    public void clickButtonListener(String name) {
        if (name.equals(getString(R.string.btn_back))) {
            this.finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_year_month_day_group:
                getYearMonthDay(true);
                break;
            case R.id.start_hour_minute_group:
                getHourMintue(true);
                break;
            case R.id.end_year_moth_day_group:
                getYearMonthDay(false);
                break;
            case R.id.end_hour_minute_group:
                getHourMintue(false);
                break;
            case R.id.trackRepaly:
                mLoactions = new ArrayList<>();
                if (checkTimeInput()) {
                    if (mTrukManger.checkNetwork(this)) {
                        if (mTrackReplayTask != null && mTrackReplayTask.getStatus() == AsyncTask.Status.RUNNING) {
                            mTrackReplayTask.cancel(true);
                        }
                        mTrackReplayTask = new TrackReplayTask();
                        mTrackReplayTask.execute(mTruckBean.getVID() + "", getTimeByDate(mStartDate),
                                getTimeByDate(mEndDate), mTrukManger.getUserType());
                    } else {
                        mTrukManger.showToastMessage(getString(R.string.toast_no_network), 1000);
                    }
                } else {
                    mTrukManger.showToastMessage(getString(R.string.date_error), 1000);
                }
                break;
        }
    }

    private String getTimeByDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        return sdf.format(date);
    }

    /**
     * 检测时间是否合符要求3天
     */
    private boolean checkTimeInput() {
        long duration = mEndDate.getTime() - mStartDate.getTime();
        if (duration <= MAX_TIME_DURATION) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据类型得到开始时间的相应年月日
     */
    public void getYearMonthDay(final boolean isStart) {
        if (isStart) {
            mTemCalender.setTime(mStartDate);//把开始date转化为Calendar
        } else {
            mTemCalender.setTime(mEndDate);//把结束date转化为Calendar
        }
        DatePickerDialog datePicker = new DatePickerDialog(
                TrackReplaySettingActivity.this,
                new DatePickerDialog
                        .OnDateSetListener() {
                    @Override
                    public void onDateSet(
                            DatePicker view,
                            int year,
                            int monthOfYear,
                            int dayOfMonth) {
                        mTemCalender.set(year, monthOfYear, dayOfMonth);
                        if (isStart) {
                            mStartDate = mTemCalender.getTime();  //把Calendar转换为开始时间
                            if (mStartDate.getTime() > System.currentTimeMillis()) {
                                mStartDate = mSystemCalendar.getTime();
                                mTemCalender.setTime(mStartDate);
                            }
                            mStartYear.setText(AppUtils.getCurrentDate(mTemCalender.getTime()));

                            if ((mEndDate.getTime() - mStartDate.getTime()) > MAX_TIME_DURATION || (mEndDate.getTime()
                                    < mStartDate.getTime())) {
                                mEndDate.setTime(MAX_TIME_DURATION + mStartDate.getTime());
                                if (mEndDate.getTime() > System.currentTimeMillis()) {
                                    mEndDate = mSystemCalendar.getTime();
                                }
                                mEndYear.setText(AppUtils.getCurrentDate(mEndDate));
                            }
                        } else {
                            mEndDate = mTemCalender.getTime();  //把Calendar转换结束为时间
                            if (mEndDate.getTime() > System.currentTimeMillis()) {
                                mEndDate = mSystemCalendar.getTime();
                                mTemCalender.setTime(mEndDate);
                            }
                            mEndYear.setText(AppUtils.getCurrentDate(mTemCalender.getTime()));
                        }
                    }
                },
                mTemCalender.get(Calendar.YEAR),
                mTemCalender.get(Calendar.MONTH),
                mTemCalender.get(Calendar.DATE));
        datePicker.show();
    }

    /**
     * 根据类型得到相应小时分钟
     */
    public void getHourMintue(final boolean isStart) {
        if (isStart) {
            mTemCalender.setTime(mStartDate);//把开始date转化为Calendar
            if (mCount == 0) {
                mHour = 0;
                mMinute = 0;
                mCount++;
            } else {
                mHour = mTemCalender.get(Calendar.HOUR_OF_DAY);  //时间结束的要得到当前时间
                mMinute = mTemCalender.get(Calendar.MINUTE);
            }
        } else {
            mTemCalender.setTime(mEndDate);//把结束date转化为Calendar
            mHour = mTemCalender.get(Calendar.HOUR_OF_DAY);  //时间结束的要得到当前时间
            mMinute = mTemCalender.get(Calendar.MINUTE);
        }
        final TimePickerDialog time1 = new TimePickerDialog(TrackReplaySettingActivity.this, new TimePickerDialog
                .OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mTemCalender.set(
                        mTemCalender.get(Calendar.YEAR),
                        mTemCalender.get(Calendar.MONTH),
                        mTemCalender.get(Calendar.DATE),
                        hourOfDay,
                        minute);
                if (isStart) {
                    mStartDate = mTemCalender.getTime();  //把Calendar转换为开始时间
                    mStartHour.setText(AppUtils.getCurrentTime(mTemCalender.getTime()));
                } else {
                    mEndDate = mTemCalender.getTime();  //把Calendar转换结束为时间
                    mEndHour.setText(AppUtils.getCurrentTime(mTemCalender.getTime()));
                }
                mMinute = minute;
                mHour = hourOfDay;
                //第一次进来开始时间为0：0 之后使用选择的时间 所以用变量
            }
        }, mHour, mMinute, true);
        time1.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoactions != null && mLoactions.size() > 0) {
            mLoactions.clear();
        }
    }

    /**
     * 开启查询历史轨迹信息的线程
     */
    public class TrackReplayTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            showNormalDialog(DialogCreater.DIALOG_PROGRESS);
            return mTrukManger.trackReplayFromServer(mLoactions, params);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.equals(Constant.RETURN_RESULT_OK)) {
                Intent intent = new Intent(TrackReplaySettingActivity.this, MapTruckPlaybackActivity.class);
//                intent.putExtra("Location", mLoactions);
                startActivity(intent);
            } else if (result.equals(Constant.CONNECT_TO_SERVER_FAILED)) {
                mTrukManger.showToastMessage(getString(R.string.toast_connect_server_failed), 1000);
            } else {
                mTrukManger.showToastMessage(result, 1000);
            }
            dismissNormalDialog();
        }
    }
}
